/**
 * @author 程麒阁
 * @description 用于获取管理员权限（适用于ant）
 * @version 1.0
 * @time 2021/11/14 14:06
 */

// !!!!! 需要在这里配置你的routes路径 !!!!!
import routes from '../router/routes.js'

export function AuthorOption (childRoutes, keyArr) {
    childRoutes.forEach(item => {
        if (keyArr.indexOf(item.key.split('-').slice(1).join('-')) < 0) {
            removeOptionByKey(routes, item.key)
        }
        if (item.children) {
            AuthorOption(item.children, keyArr)
        }
    })
}

export function getAuthorOption (childRoutes, keyArr) {
    AuthorOption(childRoutes, formatKeys(keyArr))
    return routes
}

export function getOptionByKey (routes, key) {
    let keyArr = key.split('-').slice(1)
    let deep = routes[keyArr[0]]
    try {
        keyArr.slice(1).forEach((item) => {
            deep = deep.children[item]
        })
    } catch (e) {
        deep = {}
    }
    return deep
}

export function removeOptionByKey (routes, key) {
    let keyArr = key.split('-').slice(1)
    let deep = routes[keyArr[0]]
    if (deep) {
        keyArr.slice(1, -1).forEach((item) => {
            deep = deep.children[item]
        })
        if (keyArr.length === 1) {
            delete routes[keyArr[0]]
        } else {
            if(deep){
                delete deep.children[keyArr.pop()]
            }
        }
    }
}

export function formatKeys (keyArr) {
    let result = []
    // ex：keyArr=['1-0-1']
    keyArr.forEach((item) => {
        // 进行转化 ex: 1-0-1 => ['1','0','1'] => ['1','-0','-1']
        let arr = item.split('-').slice(1).map((item, index) => index === 0 ? item : '-' + item)
        arr.forEach((item, index) => {
            // 使用截取的办法实现层级划分ex：['1','-0','-1'] => 1、1-0、1-0-1
            let term = arr.slice(0, index + 1).join('')
            // 动态规划，只有不在result数组中的才推入【去重】
                if(result.indexOf(term) === -1) result.push(term)
        })
    })
    // 返回结果
    return result
}

export default routes
